package battlelevel

import (
	"encoding/xml"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/sniperHW/kendynet"
)

type Monster struct {
	XMLName      xml.Name `xml:"monster"`
	MonsterId    int32    `xml:"monster_id"`
	MonsterCount int32    `xml:"monster_count"`
}

type MonsterList struct {
	XMLName  xml.Name  `xml:"monster_list"`
	Monsters []Monster `xml:"monster"`
}

type BattleLevel struct {
	XMLName       xml.Name    `xml:"battle_level"`
	BattleLevelID int32       `xml:"id"`
	MonsterList   MonsterList `xml:"monster_list"`
}

var BattleLevelDefs map[int32]BattleLevel

func init() {
	BattleLevelDefs = map[int32]BattleLevel{}
}

func GetDef(battleLevelID int32) *BattleLevel {
	if b, ok := BattleLevelDefs[battleLevelID]; ok {
		return &b
	} else {
		return nil
	}
}

func getFilelist(path string) bool {
	err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
		if f != nil && !f.IsDir() {
			s := len(path)
			if s > 4 && ".xml" == path[s-4:] {
				content, e := ioutil.ReadFile(path)
				if e != nil {
					kendynet.Errorf("load %s error:%s\n", path, e.Error())
					return e
				}
				var battleLevel BattleLevel
				e = xml.Unmarshal(([]byte)(content), &battleLevel)
				if e != nil {
					kendynet.Errorf("load %s error:%s\n", path, e.Error())
					return e
				}

				BattleLevelDefs[battleLevel.BattleLevelID] = battleLevel
			}
		}
		return nil
	})
	if err != nil {
		return false
	} else {
		return true
	}
}

func Load(path string) bool {
	return getFilelist(path)
}
